import React, { Component } from "react";
import MainLayout from "../../../../component/mainLayout/mainLayout";
import Button from "../../../../component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "../../../../component/verCode/index";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList,
	checkUserBankInfo
} from "../../../../Redux/Action/bank/bank";
import { InterfaceG } from "../../../../config/Config";
import BackModal from "../../../../component/backModal/index";
import yhTools from "../../../../tools/yh";
const BankIcon = require("../../../../images/icon/helpTip.png");

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);

const agreementPageMap = {
	huaTongAccount: "/huaTongBankElectronicAccountServiceAgreement",
	taxStatement: "/individualTaxResidentStatusStatement",
	pay: "/agreementoflianyintong"
};

const backHomeMap = {
	601: "/xhfHomeNoCredit",
	802: "/xhdHome",
	1: "/walletHome",
	602: "/xhfHomeNoCredit"
};

const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();
@verCode()
@connect(
	state => ({
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer
	}),
	dispatch => ({
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun)),
		checkUserBankInfo: (value, fun) => dispatch(checkUserBankInfo(value, fun))
	})
)
class AddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: "",
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true
		};
	}

	componentDidMount = () => {
		const from = yhTools.getUrlParam("from");
		const fromBankList = from === "bankList";
		// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
		this.setState(
			{
				from,
				channelCode:
					this.props.lnid == "802" ? "ll" : fromBankList ? "ll" : "YHB"
			},
			() => {
				const { checkUserBankInfo, getSupportedBankList } = this.props;
				const { channelCode } = this.state;
				if (fromBankList) {
					// !ocrInfo.userName && checkUserBankInfo({ channelCode });
					// TODO 优化，支付换卡和开户绑卡银行卡列表不一样
					checkUserBankInfo({ channelCode });
				} else {
					getSupportedBankList({ channelCode });
				}
			}
		);
	};
	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	getMsgCode = () => {
		if (this.props.lnid == "802" && this.state.from == "liveness") {
			this.xhdSendCode();
		} else {
			this.sendMsgCode();
		}
	};
	sendMsgCode = () => {
		const { channelCode, accountNo, userBankPhone, from } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(userBankPhone)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(from === "bankList" ? 120 : 60); //连连和华通验证码时间不一样
		const params = {
			channelCode,
			accountNo
		};
		let objs = {
			url:
				from === "liveness"
					? InterfaceG.openAccountSendCode
					: InterfaceG.xhdSendCode,
			params:
				from === "liveness"
					? {
							...params,
							bankMobilePhone: userBankPhone
					  }
					: {
							...params,
							userBankPhone
					  },
			_alertShow: false
		};
		Toast.loading("加载中...", 100);

		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { messageSerialNumber, verifier } = res.data;
				this.setState({
					messageSerialNumber,
					verifier,
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	//小辉贷发送验证码
	xhdSendCode() {
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		const { userBankPhone, from, accountNo } = this.state;
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(userBankPhone)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(from === "bankList" ? 120 : 60); //连连和华通验证码时间不一样
		let objs = {
			url: InterfaceG.xhdSendCode,
			params: {
				mobilePhone: this.state.userBankPhone,
				lnid: this.props.lnid,
				accountNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				// const { messageSerialNumber, verifier } = res.data;
				this.setState({
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	openAccount = () => {
		const { applyNo, lnid } = this.props;
		const {
			accountNo,
			verifyCode,
			userBankPhone,
			messageSerialNumber
		} = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.openAccount,
				params: {
					applyNo,
					lnid,
					cardNo: accountNo,
					verifyCode,
					bankMobilePhone: userBankPhone,
					messageSerialNumber,
					channelCode: "YHB"
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(async res => {
				Toast.hide();
				this.setState({ canSubmit: true });

				if (res.code === "0") {
					const cardNo = res.data.electronicCardNo;
					this.props.history.push(
						`/openAccountResult?status=success&cardNo=${cardNo}`
					);
				} else if (
					// res.code === "60007" ||
					// res.code === "00007" ||
					// res.code === "306003" ||
					// res.code === "00053" ||
					// res.code === "99999" ||
					// res.code === "99998" ||
					// res.code === "99000"
					res.code === "2"
				) {
					Toast.info(res.message);
				} else {
					this.props.history.push(`/openAccountResult?status=fail`);
				}
			});
		}
	};
	InputOnChange = (key, value) => {
		this.setState({
			[key]: submitCardRegexp(value)
		});
	};

	checkCanSubmit = (cardNo, phoneNum, verifyCode) => {
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(cardNo)) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(phoneNum)) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}

		return true;
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return true;
		} else if (res.code === "70010") {
			return false;
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}
	addNewBankFn = async () => {
		const from = yhTools.getUrlParam("from");
		// 防止重复提交，待优化
		const {
			channelCode,
			accountNo,
			userBankPhone,
			verifyCode,
			messageSerialNumber,
			verifier
		} = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.addNewCard,
				params: {
					channelCode,
					accountNo,
					userBankPhone,
					verifyCode,
					messageSerialNumber,
					verifier,
					lnid: from == "liveness" ? this.props.lnid : ""
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				Toast.hide();
				if (res.code === "0") {
					this.props.getSelectedBankList({ channelCode });
					setTimeout(() => {
						this.props.history.goBack();
					}, 0);
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	saveBank = () => {
		const from = yhTools.getUrlParam("from");
		if (from === "liveness") {
			if (this.props.lnid == "802") {
				this.xhdSubmit();
			} else {
				this.openAccount();
			}
		} else {
			this.addNewBankFn();
		}
	};
	//小辉贷四要素认证
	xhdSubmit = () => {
		const { accountNo, verifyCode, userBankPhone } = this.state;
		if (this.checkCanSubmit(accountNo, userBankPhone, verifyCode)) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.xhdBindCard,
				params: {
					userBankPhone,
					lnid: this.props.lnid,
					accountNo,
					verifyCode
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				Toast.hide();
				if (res.code === "0") {
					this.props.history.push("/editPersonalInfo");
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	//查看协议
	openContract = (e, type) => {
		e.stopPropagation();
		const { userName, idNo } = this.props.ocrInfo;
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		const paramsHuaTong = {
			...commonParams,
			signName: userName
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: type === "huaTongAccount" ? paramsHuaTong : commonParams
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isBackModalVisible: false
		});
		!booleanValue && this.props.history.push(backHomeMap[this.props.lnid]);
	};
	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};
	render() {
		const {
			isVisible,
			isBackModalVisible,
			userBankPhone,
			from,
			accountNo,
			hasSendCode
		} = this.state;
		const { supportedBankList, ocrInfo, lnid } = this.props;
		const _pageParams = {
			header: {
				title: "添加银行卡"
			},
			componentDidRecover: () => {
				const from = yhTools.getUrlParam("from");
				if (from == "bankList") {
					this.setState({
						userBankPhone: "",
						verifyCode: "",
						accountNo: "",
						from: from
					});
				}
			},
			cacheLifecycles: this.props.cacheLifecycles,
			isModal: from === "liveness",
			history: this.props.history
		};
		const { countDown, isClick } = this.props.verCode;
		const userName =
			ocrInfo.userName &&
			"*".repeat(ocrInfo.userName.length - 1) + ocrInfo.userName.slice(-1);
		return (
			<div>
				<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
					<BackModal
						product={lnid}
						isVisible={isBackModalVisible}
						onClick={this.onModalClick}
					/>
					<div className="xhf-add-bank-wrapper">
						<div className="add-bank-container">
							<InputItem
								className="my-input"
								defaultValue={userName}
								value={userName}
								disabled={true}
							>
								姓名
							</InputItem>
							{/* 23包括空格 */}
							<InputItem
								maxLength="23"
								className="my-input my-clear1"
								placeholder="请输入银行卡号"
								type="number"
								clear
								defaultValue={accountNo}
								onChange={this.InputOnChange.bind(this, "accountNo")}
							>
								银行卡号
								<img
									alt="guide"
									className="icon-help"
									src={BankIcon}
									onClick={() => this.toggleVisible(true)}
								/>
							</InputItem>
							<InputItem
								clear
								type="phone"
								placeholder="请填写预留手机号"
								defaultValue={userBankPhone}
								className="my-input"
								onChange={this.InputOnChange.bind(this, "userBankPhone")}
							>
								预留手机号
							</InputItem>
							<InputItem
								clear
								placeholder="请输入验证码"
								maxLength={6}
								minLength={6}
								pattern="[0-9]{6}"
								type="tel"
								className="my-input my-clear2"
								onChange={this.InputOnChange.bind(this, "verifyCode")}
							>
								验证码
								<span className="get-code" onClick={this.getMsgCode}>
									{/* {isClick ? "获取验证码" : countDown} */}

									{isClick
										? hasSendCode
											? "重新发送"
											: "获取验证码"
										: countDown}
								</span>
							</InputItem>
							<div
								className="agree-wrapper"
								style={{ display: this.props.lnid == "802" ? "none" : "block" }}
							>
								{from === "liveness" && (
									<span className="multi-line">
										<a className="huise">查看</a>
										<a
											className="font-link"
											onClick={e => this.openContract(e, "huaTongAccount")}
										>
											《福建华通银行电子账户服务协议》
										</a>
										<a
											className="font-link"
											onClick={e => this.openContract(e, "taxStatement")}
										>
											《个人税收居民身份声明》
										</a>
										<a className="huise">，并承诺本人是中国税收居民</a>
									</span>
								)}
								{from === "bankList" && (
									<span className="multi-line">
										<a className="huise">查看</a>
										<a
											className="font-link one-line"
											onClick={e => this.openContract(e, "pay")}
										>
											《支付连连银通银行卡支付服务协议》
										</a>
									</span>
								)}
							</div>

							<Modal
								visible={isVisible}
								transparent
								maskClosable={true}
								title="银行卡支持列表"
								closable={true}
								onClose={() => this.toggleVisible(false)}
								className="bank-list-modal"
							>
								<div style={{ height: 300, overflow: "scroll" }}>
									{supportedBankList.map(item => (
										<BankItem item={item} key={Math.random()} />
									))}
								</div>
							</Modal>

							<Button style={{ marginTop: "60px" }} onClick={this.saveBank}>
								同意协议并添加
							</Button>
						</div>
					</div>
				</MainLayout>
			</div>
		);
	}
}
export default AddBank;
